package com.itdaan.portal.business.controller;

import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.itdaan.portal.business.domain.Permission;
import com.itdaan.portal.business.service.PermissionService;
import com.itdaan.portal.common.exception.ServiceException;

/**
 * 权限控制业务控制类
 * @author www.itdaan.com
 */
@Controller
@RequestMapping("/user/permission")
public class PermissionController {
	
	private Logger logger = LoggerFactory.getLogger(PermissionController.class);
	
	@Autowired
	private PermissionService permissionService;
	
	@RequestMapping(value = "edit")
	public String edit(
			@ModelAttribute("preloadPermission") Permission permission,
			Model model) {
		model.addAttribute("permission", permission);
		return "user/permission_edit";
	}
	
	@RequiresPermissions("permission:save")
	@RequestMapping(value = "save", method = RequestMethod.POST)
	public String save(
			@ModelAttribute("preloadPermission") Permission permission) {
		if (permission.getId() == 0) {// 新增
			try {
				permissionService.insert(permission);
			} catch (ServiceException e) {
				logger.error("插入权限失败：{}" , e.toString());
			}
		} else {// 修改
			try {
				permissionService.update(permission);
			} catch (ServiceException e) {
				logger.error("修改权限失败：{}" , e.toString());
			}
		}
		return "redirect:/user/permission";
	}
	
	@RequiresPermissions("permission:delete")
	@RequestMapping(value = "delete")
	public String delete(@RequestParam("ids") String ids) {
		try {
			permissionService.deleteByIds(ids);
		} catch (ServiceException e) {
			logger.error("删除权限失败：{}" , e.toString());
		}
		return "redirect:/user/permission";
	}
	
	@RequestMapping(value = StringUtils.EMPTY)
	public String list(Model model) {
		List<Permission> permissions = new ArrayList<Permission>();
		try {
			permissions = permissionService.getAll();
		} catch (ServiceException e) {
			logger.error("查询权限信息失败：{}",e.toString());
		}
		model.addAttribute("permissions", permissions);
		return "user/permission_list";
	}
	
	@ModelAttribute("preloadPermission")
	public Permission getPermission(
			@RequestParam(value = "id", required = false) Integer id) {
		if (id != null && id != 0) {
			try {
				return permissionService.getById(id);
			} catch (ServiceException e) {
				logger.error("查询权限信息失败：{}" ,e.toString());
			}
		}
		return new Permission();
	}
}
